//============================================================================
// Name        : state_pattern.cpp
// Author      : Tony
// Version     :
// Copyright   : GPLv2
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
using namespace std;
class StateA;
class StateB;
class Context;

class State
{
public:
	virtual ~State(){}
	virtual void handle(Context* context) = 0;
};

class StateA : public State
{
public:
	static State* Instance()
	{
		return new StateA();
	}
	virtual void handle(Context* context);

private:
	StateA(){}

};

class StateB : public State
{
public:
	static State* Instance()
	{
		return new StateB();
	}
	virtual void handle(Context* context);
private:
	StateB(){}
};


class Context
{
public:
	Context(){
		_state = StateA::Instance();
	}
	virtual ~Context(){}

	void changeState(State* state)
	{
		_state = state;
	}
	void request()
	{
		_state->handle(this);
	}
private:
	State* _state;
};

void StateA::handle(Context* context)
{
	cout<<"do something in state A"<<endl;
	cout<<"Done: change to state B"<<endl;
	context->changeState(StateB::Instance());
}

void StateB::handle(Context* context)
{
	cout<<"do something in state B"<<endl;
	cout<<"Done: change to state A"<<endl;
	context->changeState(StateA::Instance());
}

int main() {
	Context* c = new Context();
	c->request();
	cout<<"================"<<endl;
	c->request();
	cout<<"================"<<endl;
	c->request();
	delete c;
	return 0;
}
